<template>
  <div>
    <h2>组织详情</h2>
    <p><strong>组织名称：</strong>{{ org.name }}</p>
    <p><strong>组织ID：</strong>{{ org.orgId }}</p>
    <p><strong>邮箱：</strong>{{ org.email }}</p>
    <p><strong>C级管理员ID：</strong>{{ org.cadminId }}</p>
    <p><strong>B级管理员ID：</strong>{{ org.badminId }}</p>
    <div style="margin-top: 20px;">
      <el-button
        type="primary"
        v-if="!joined"
        @click="joinOrg"
      >加入组织</el-button>
      <el-button
        type="danger"
        v-if="joined"
        @click="withdrawOrg"
      >退出组织</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const route = useRoute()
const stuId = localStorage.getItem('loginId')
const org = ref({})
const joined = ref(false)

const fetchOrgDetail = async () => {
  try {
    // 通过组织名和学生ID获取组织详情和加入状态
    const res = await axios.get(`http://localhost:8080/student/${stuId}/${route.params.orgId}/getOrgById`)
    if (res.data && res.data.data) {
      org.value = res.data.data
      if (res.data.code === 200) {
        joined.value = false
      } else if (res.data.code === 201) {
        joined.value = true
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : '获取组织详情失败')
      }
    } else {
      ElMessage.error('获取组织详情失败')
    }
  } catch (e) {
    ElMessage.error('获取组织详情失败')
  }
}

// 加入组织
const joinOrg = async () => {
  try {
    const res = await axios.post(
      `http://localhost:8080/student/${stuId}/addOrg`,
      Number(org.value.orgId),
      { headers: { 'Content-Type': 'application/json' } }
    )
    if (res.data && res.data.code === 200) {
      ElMessage.success('加入成功')
      joined.value = true
    } else {
      ElMessage.error(res.data && res.data.msg ? res.data.msg : '加入失败')
    }
  } catch (e) {
    ElMessage.error('加入失败')
  }
}

// 退出组织
const withdrawOrg = async () => {
  try {
    const res = await axios.delete(`http://localhost:8080/student/${org.value.orgId}/${stuId}/withdrawOrg`)
    if (res.data && res.data.code === 200) {
      ElMessage.success('退出成功')
      joined.value = false
    } else {
      ElMessage.error(res.data && res.data.msg ? res.data.msg : '退出失败')
    }
  } catch (e) {
    ElMessage.error('退出失败')
  }
}

onMounted(fetchOrgDetail)
</script>